package cn.gson.crm.controller.beforesale;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import cn.gson.crm.model.dao.CustomerDao;
import cn.gson.crm.model.dao.EmployeeDao;
import cn.gson.crm.model.dao.OpportunityDao;
import cn.gson.crm.model.dao.QuotationDao;
import cn.gson.crm.model.dao.QuotationDetailsDao;
import cn.gson.crm.model.entity.Quotation;
import cn.gson.crm.model.entity.QuotationDetails;


/**
 * 报价
 * 
 * @author hzl
 * @date 2018年4月23日
 * @time 下午9:25:02
 */
@Controller
@RequestMapping("quotation")
public class QuotationController {

	@Autowired
	OpportunityDao opportunityDao;
	
	@Autowired
	CustomerDao customerDao;
	
	@Autowired
	EmployeeDao empDao;

	@Autowired
	OpportunityDao oppDao;

	@Autowired
	QuotationDao quotationDao;
	@Autowired
	QuotationDetailsDao quotationDetailsDao;
	
	@RequestMapping
	public String quotation() {
		return "beforesale/quotation/list";
	}

	@RequestMapping("all")
	@ResponseBody
	public Map<String,Object> all(){
		Map<String, Object> data = new HashMap<>();
		List<Quotation> list = (List<Quotation>) quotationDao.findAll();
		PageInfo<Quotation> info = new PageInfo<>(list);
		data.put("rows", info.getList());
		data.put("total", info.getTotal());
		return data;
	}

	/*@RequestMapping({"form","form/{id}"})
	public String form(@PathVariable(required=false) Long id,Model model) {
		//查询机会列表
		List<SalesOpportunity> opportunityList = (List<SalesOpportunity>)opportunityDao.findAll();
		List<Customer> customerList = (List<Customer>)customerDao.findAll();
		model.addAttribute("opportunityList", opportunityList);
		model.addAttribute("customerList", customerList);
	}*/	


	// 获取未审核的报价单，分页
	@RequestMapping("audit")
	@ResponseBody
	public Map<String, Object> getauditlist(@RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "20") int rows) {
		System.out.println("你看，这里执行了");
		PageRequest pr = new PageRequest(page - 1, rows, new Sort(Direction.DESC, "id"));
		Page<Quotation> quotation = quotationDao.findByApproval("未审批", pr);
		Map<String, Object> data = new HashMap<>();
		data.put("rows", quotation.getContent());
		data.put("total", quotation.getTotalElements());
		return data;
	}

	@RequestMapping("form2")
	public String form2(@PathVariable(required = false) Long id, Model model) {
		
		return "beforesale/quotation/quotation_edit";
	}
	@RequestMapping("form")
	public String form(@PathVariable(required = false) Long id, Model model) {
		return "beforesale/quotation/form";
	}
	
	@PostMapping("save")
	@ResponseBody
	@Transactional
	public JSONObject save(@Valid Quotation quotation,BindingResult br) {
		JSONObject jo = new JSONObject();
		if(br.hasErrors()) {
			jo.put("err","校验失败！");
		}else {
			if(quotation.getId()==null) {
				quotation.setTime(new Date());
				quotation.setApproval("未审批");
			}
			quotationDao.save(quotation);
			jo.put("success", true);
			jo.put("newOrder", quotation);
		}
		return jo;
	}
	
	//保存报价单
	@PostMapping("save2")
	@ResponseBody
	public JSONObject savequo(@Valid Quotation quotation,BindingResult br,
			@RequestParam(value = "customerid", required = false) Long cid,
			@RequestParam(value = "salesOppid", required = false) Long salesOppid,
			@RequestParam(value = "employeeid", required = false) Long employeeid,
			HttpServletRequest req) {
		HttpSession session = req.getSession();
		JSONObject result = new JSONObject();
		if (br.hasErrors()) {
			System.out.println(br);
			result.put("err", "校验失败！");
		} else {
			if(salesOppid!=null) {
				quotation.setSalesOpp(oppDao.findOne(salesOppid));
			}
			if(cid!=null) {
				quotation.setCustomer(customerDao.findOne(cid));
			}
			if(employeeid!=null) {
				quotation.setEmployee(empDao.findOne(employeeid));
			}
			quotationDao.save(quotation);
		}
		return result;
		
	}
	
	
	/**
	 * 查看报价单详情
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("detail/{id}")
	public String detail(@PathVariable(name="id")Long id,Model model) {
		Quotation quotation = quotationDao.findOne(id);
		List<QuotationDetails> list = quotationDetailsDao.findByQuotation(quotation);
		model.addAttribute("q", quotation);
		model.addAttribute("details", list);
		return "beforesale/quotation/detail";
	}
	
	// 添加订单明细表
	@GetMapping("/adddetail/{id}")
	public String addorderdetail(HttpServletRequest req, @PathVariable(name = "id") Long id) {
		req.setAttribute("quotation", quotationDao.findOne(id));
		return "beforesale/quotation/add_detail";
	}
	
	@PostMapping("delete/{id}")
	@ResponseBody
	@Transactional
	public JSONObject deleteQuotation(@PathVariable(name="id")Long id) {
		JSONObject obj = new JSONObject();
		if(id!=null&&quotationDao.findOne(id)!=null) {
			Quotation quotation = quotationDao.findOne(id);
			quotation.setDelete(true);
			quotationDao.save(quotation);
			obj.put("success",true);
			return obj;
		}
		return obj;
	}
	
}
